package org.apache.ocean.name;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.ocean.CElement;
import org.apache.ocean.XMLUtil;
import org.apache.ocean.name.NamesInfosGroup.NameInfoIDComparator;
import org.jdom.Element;

/**
 * 
 * @author jasonr
 */
public class ReportedNameInfos implements CElement {
	public String fromNameID;
	public List<NameInfo> nameInfos;
	public Date timestamp;

	public ReportedNameInfos(Element root) throws Exception {
		fromNameID = root.getAttributeValue("fromNameID");
		timestamp = XMLUtil.getAttributeDate("timestamp", root);
		nameInfos = new ArrayList<NameInfo>();
		for (Element element : XMLUtil.getChildren(root)) {
			nameInfos.add(new NameInfo(element));
		}
	}

	public NameInfo chooseMasterNameInfo() {
		NameInfo nameInfoWithHighestReplicationID = null;
		Collections.sort(nameInfos, new NameInfoIDComparator());
    for (NameInfo nameInfo : nameInfos) {
    	if (nameInfo.highestReplicationIDDatabase != null) {
    		if (nameInfoWithHighestReplicationID == null) {
    			nameInfoWithHighestReplicationID = nameInfo;
    		} else {
    			if (nameInfo.highestReplicationIDDatabase != null && nameInfoWithHighestReplicationID.highestReplicationIDDatabase != null) {
    				if (nameInfo.highestReplicationIDDatabase.compareTo(nameInfoWithHighestReplicationID.highestReplicationIDDatabase) > 0) {
    					nameInfoWithHighestReplicationID = nameInfo;
    				}
    			}
    		}
    	}
    }
    return nameInfoWithHighestReplicationID;
	}

	public Element toElement() throws Exception {
		Element root = new Element("reportednameinfos");
		XMLUtil.setAttribute("fromNameID", fromNameID, root);
		XMLUtil.setAttribute("timestamp", timestamp, root);
		for (NameInfo nameInfo : nameInfos)
			root.addContent(nameInfo.toElement());
		return root;
	}

	public String toString() {
		return ReflectionToStringBuilder.toString(this);
	}

	public ReportedNameInfos(String fromNameID, List<NameInfo> nameInfos, Date timestamp) {
		this.fromNameID = fromNameID;
		this.nameInfos = nameInfos;
		this.timestamp = timestamp;
	}
}
